package org.niit.app.online

import org.apache.kafka.clients.consumer.ConsumerRecord
import org.apache.spark.SparkConf
import org.apache.spark.sql.SparkSession
import org.apache.spark.streaming.dstream.InputDStream
import org.apache.spark.streaming.kafka010.{ConsumerStrategies, KafkaUtils, LocationStrategies}
import org.apache.spark.streaming.{Seconds, StreamingContext}
import org.niit.service.RealtimeAnalysisService
import org.niit.util.ConfigUtil

/**
 * 实时分析应用入口
 */
object RealTimeAnalyseApp {
  def main(args: Array[String]): Unit = {
    // 创建SparkSession
    val spark = SparkSession
      .builder()
      .appName("TakeawayRealtimeAnalysis")
      .master("local[*]")
      .config("spark.sql.warehouse.dir", "spark-warehouse")
      .getOrCreate()
    
    // 设置日志级别
    spark.sparkContext.setLogLevel("WARN")
    
    // 创建StreamingContext，批处理时间为10秒
    val ssc = new StreamingContext(spark.sparkContext, Seconds(10))
    
    try {
      println("===================== 外卖订单实时分析应用 ======================")
      println("正在启动Kafka消费者，等待接收数据...")
      
      // 配置Kafka连接参数
      val kafkaParams = Map[String, Object](
        "bootstrap.servers" -> ConfigUtil.kafkaBootstrapServers,
        "key.deserializer" -> "org.apache.kafka.common.serialization.StringDeserializer",
        "value.deserializer" -> "org.apache.kafka.common.serialization.StringDeserializer",
        "group.id" -> ConfigUtil.kafkaGroupId,
        "auto.offset.reset" -> ConfigUtil.kafkaAutoOffsetReset,
        "enable.auto.commit" -> (false: java.lang.Boolean)
      )
      
      // 订阅Kafka主题
      val topics = Array(ConfigUtil.kafkaTopic)
      
      // 创建DStream
      val stream: InputDStream[ConsumerRecord[String, String]] = KafkaUtils.createDirectStream[String, String](
        ssc,
        LocationStrategies.PreferConsistent,
        ConsumerStrategies.Subscribe[String, String](topics, kafkaParams)
      )
      
      // 提取消息内容
      val orderStream = stream.map(record => record.value())
      
      // 处理实时订单数据
      RealtimeAnalysisService.processRealtimeOrders(spark, orderStream)
      
      // 启动流处理
      ssc.start()
      ssc.awaitTermination()
    } catch {
      case e: Exception =>
        println("实时分析过程中发生错误:")
        e.printStackTrace()
    }
  }
} 